/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.security.checkrequest.policy;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * sql语句过滤策略
 *
 * @see CheckPolicy
 * @author yoara
 */
public class SQLCheckPolicy implements CheckPolicy {
    private static ThreadLocal<Pattern> threadLocal
            = new ThreadLocal<Pattern>(){
        @Override
        protected Pattern initialValue() {
            return Pattern.compile(
                    "(\\s*select\\s+)|(\\s*insert\\s+)|(\\s*delete\\s+)|(\\s*from\\s+)" +
                            "|(\\s*drop\\s+)|(\\s*update\\s+)|(\\s*truncate\\s+)",
                    Pattern.CASE_INSENSITIVE);
        }
    };

    @Override
    public void doCheck(CheckResult result) {
        String params = result.getCheckObject();
        Matcher matcher = threadLocal.get().matcher(params);
        if(matcher.find(0)){
            result.setMsg("包含特殊的字符类型"+matcher.group(0)+"，请重新输入");
            result.setReplaceObject(matcher.replaceAll(""));
            result.setIsValid(false);
        }
    }
}
